/*
 *
 *  * | Licensed 未经许可不能去掉「OPENIITA」相关版权
 *  * +----------------------------------------------------------------------
 *  * | Author: xw2sy@163.com
 *  * +----------------------------------------------------------------------
 *
 *  Copyright [2024] [OPENIITA]
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 * /
 */

package cc.iotkit.data.service;

import cc.iotkit.common.api.PageRequest;
import cc.iotkit.common.api.Paging;
import cc.iotkit.common.satoken.utils.LoginHelper;
import cc.iotkit.common.utils.StringUtils;
import cc.iotkit.data.dao.AlertRecordRepository;
import cc.iotkit.data.dao.IJPACommData;
import cc.iotkit.data.manager.IAlertRecordData;
import cc.iotkit.data.model.TbAlertRecord;
import cc.iotkit.data.util.PredicateBuilder;
import cc.iotkit.model.alert.AlertRecord;
import com.querydsl.core.QueryResults;
import com.querydsl.core.types.Predicate;
import com.querydsl.core.types.Projections;
import com.querydsl.core.types.dsl.Expressions;
import com.querydsl.jpa.impl.JPAQuery;
import com.querydsl.jpa.impl.JPAQueryFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Service;

import java.time.ZoneId;
import java.util.List;

import static cc.iotkit.data.model.QTbAlertRecord.tbAlertRecord;
import static cc.iotkit.data.model.QTbDeviceInfo.tbDeviceInfo;
import static cc.iotkit.data.model.QTbProduct.tbProduct;
import static cc.iotkit.data.model.QTbProductModel.tbProductModel;
import static cc.iotkit.data.model.QTbSysTenant.tbSysTenant;

@Primary
@Service
public class AlertRecordDataImpl implements IAlertRecordData, IJPACommData<AlertRecord, Long> {

    @Autowired
    private AlertRecordRepository alertRecordRepository;

    @Autowired
    private JPAQueryFactory jpaQueryFactory;

    @Override
    public JpaRepository getBaseRepository() {
        return alertRecordRepository;
    }

    @Override
    public Class getJpaRepositoryClass() {
        return TbAlertRecord.class;
    }

    @Override
    public Class getTClass() {
        return AlertRecord.class;
    }

    private static Predicate genPredicate(AlertRecord data) {
        return PredicateBuilder.instance()
                .and(!LoginHelper.isSuperAdmin(),  () -> tbAlertRecord.tenantId.eq(Long.valueOf(LoginHelper.getTenantId())))
                .and(StringUtils.isNotBlank(data.getName()), () -> tbAlertRecord.name.like(data.getName()))
                .and(StringUtils.isNotBlank(data.getLevel()), () -> tbAlertRecord.level.eq(data.getLevel()))
                .and(data.getBeginTime()!=null, () -> tbAlertRecord.alertTime.goe(data.getBeginTime().atZone(ZoneId.systemDefault()).toInstant().toEpochMilli()))
                .and(data.getEndTime()!=null, () -> tbAlertRecord.alertTime.loe(data.getEndTime().atZone(ZoneId.systemDefault()).toInstant().toEpochMilli()))
                .and(StringUtils.isNotBlank(data.getDetails()), () -> tbAlertRecord.details.like("%"+data.getDetails()+"%"))
                .build();
    }

    public JPAQuery<AlertRecord> buildSelect(AlertRecord data) {
        Predicate predicate = genPredicate(data);
        return jpaQueryFactory.select(Projections.bean(AlertRecord.class,
                        tbAlertRecord.id,tbAlertRecord.uid,tbAlertRecord.deviceId, tbAlertRecord.name, tbAlertRecord.level,tbAlertRecord.alertTime,
                        tbAlertRecord.tenantId,tbAlertRecord.createDept,tbAlertRecord.readFlg,tbAlertRecord.details,
                        tbSysTenant.companyName,
                        Expressions.as(tbProduct.name, Expressions.stringPath("productName")),
                        tbProduct.productKey,tbDeviceInfo.deviceName,tbDeviceInfo.robotSn,tbDeviceInfo.modelId,
                        Expressions.as(tbProductModel.model, Expressions.stringPath("modelName"))

                ))
                .from(tbAlertRecord)
                .leftJoin(tbDeviceInfo).on(tbDeviceInfo.id.eq(tbAlertRecord.deviceId))
                .leftJoin(tbProduct).on(tbProduct.productKey.eq(tbDeviceInfo.productKey))
                .leftJoin(tbProductModel).on(tbDeviceInfo.modelId.eq(tbProductModel.id))
                .leftJoin(tbSysTenant).on(tbSysTenant.id.eq(tbAlertRecord.tenantId))
                .where(predicate)
                .orderBy(tbAlertRecord.id.desc());
    }
    @Override
    public List<AlertRecord> selectAlertRecord(AlertRecord query) {
        List<AlertRecord> results = buildSelect(query).fetch();
        return results;
    }
    @Override
    public Paging<AlertRecord> selectAlertConfigPage(PageRequest<AlertRecord> request) {
        AlertRecord data = request.getData();
        QueryResults<AlertRecord> results = buildSelect(data)
                .orderBy(tbAlertRecord.id.desc())
                .limit(request.getPageSize())
                .offset(request.getOffset()).fetchResults();
        return new Paging<>(results.getTotal(), results.getResults());
    }

    public long count(){
        return alertRecordRepository.count();
    }
}
